package com.mystudy.dataStructure.queue;


public class LinkedListQueue<E> implements Queue<E> {
    private Node head;
    private Node tail;
    private int size;

    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }


    @Override
    public void enqueue(E e) {
        Node node = new Node(e);
        if (tail == null) {
            tail = node;
            head = tail;
        } else {
            tail.next = node;
            tail = tail.next;
        }
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("can not deque from an empty dqeue");

        }
        Node refNode = head;
        head = head.next;
        refNode.next = null;//释放引用防止出队的元素不被回收
        if (head == null) {
            tail = null;
        }
        size -- ;
        return refNode.data;
    }

    @Override
    public E getFront() {
        if(isEmpty()){
            throw new IllegalArgumentException("can not deque from an empty dqeue");
        }
        return head.data;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }


    @Override
    public String toString() {
        StringBuilder ref = new StringBuilder();
        ref.append("Queue front");
        for(Node cur = head;cur != null;cur = cur.next){
            ref.append(cur.data+"->");
        };
        ref.append("Null tail");
        return ref.toString();
    }

    private class Node {
        public E data;
        public Node next;

        public Node(E data, Node next) {
            this.data = data;
            this.next = next;
        }

        public Node(E data) {
            this(data, null);
        }

        public Node() {
            this(null);
        }


        @Override
        public String toString() {
            return data.toString();
        }
    }

}
